const app = getApp();
const towxImg = require('../../../utils/towxImg');

// pages/index/detail/detail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: "",
    scrollTop: 0,
    title: '',
    article: ''
  },

  async getData(id, type) {
    var c1 = new wx.cloud.Cloud({
      resourceAppid: "wx9a44ab6c8170142c",
      resourceEnv: "love-0g1b6yqybf5521f5",
    });
    await c1.init();

    c1.downloadFile({
      fileID: 'cloud://love-0g1b6yqybf5521f5.6c6f-love-0g1b6yqybf5521f5-1316718936/md/experience' + id + '.md'
    }).then(res => {
      // console.log(res.tempFilePath)
      let fs = wx.getFileSystemManager()
      let result = fs.readFileSync(res.tempFilePath, "utf-8")

      let article = app.towxml(result, type, {
        base: '',
        theme: 'light',
        events: {
          tap: (e) => {
            console.log('tap', e);
          }
        }
      });

      this.setData({ article }, () => wx.hideLoading())
    }).catch(err => {
      wx.hideLoading();
      wx.showModal({
        title: '请求错误',
        content: err.errMsg,
        showCancel: false,
        complete: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      })
    })
  },

  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading({
      title: 'Loading',
    })
    let { id, type, article, title } = options;
    // 请求云 md 文件
    // this.getData(id, type);

    if (article) {
      article = article.replaceAll('\\n', '\n').replaceAll('\\=', '=').replaceAll('\\{', '{').replaceAll('\\}', '}').replaceAll('\\t', '\t');
    } else {
      wx.hideLoading();
      wx.showModal({
        title: '错误提示',
        content: '暂无内容',
        showCancel: false,
        complete: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      })
    }

    let result = towxImg.dealWithRichText(article, type);

    // let result = app.towxml(article, type, {
    //   base: '',
    //   theme: 'light',
    //   events: {
    //     tap: (e) => {
    //       console.log('tap', e);
    //     }
    //   }
    // });
    this.setData({ article: result, title }, () => wx.hideLoading())
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const theme = wx.getStorageSync("systemTheme");
    this.setData({
      theme,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

});
